<template>
  <div class="controls">
    <input
      autocomplete="off"
      class="itxt"
      :value="currentValue"
      @blur="handleBlur"
      @keyup.enter="handleBlur"
    />
    <a
      :class="{
        plus: true,
        disabled: this.currentValue === this.max,
      }"
      @click="currentValue++"
      >+</a
    >
    <a
      :class="{
        mins: true,
        disabled: this.currentValue === this.min,
      }"
      @click="currentValue--"
      >-</a
    >
  </div>
</template>

<script>
export default {
  name: "InputNumber",
  data() {
    return {
      currentValue: 1,
    };
  },
  props: {
    value: {
      type: Number,
      default: 1,
    },
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 10,
    },
  },
  methods: {
    handleBlur(e) {
      this.currentValue = +e.target.value;
    },
  },
  watch: {
    currentValue(newValue, oldValue) {
      if (Number.isNaN(newValue)) {
        this.currentValue = oldValue;
      } else if (newValue > this.max) {
        this.currentValue = this.max;
      } else if (newValue < this.min) {
        this.currentValue = this.min;
      }
      //触发外层组件num的更新
      this.$emit("input", this.currentValue);
    },
  },
};
</script>

<style lang="less" scoped>
.controls {
  width: 48px;
  position: relative;
  float: left;
  margin-right: 15px;

  .itxt {
    width: 38px;
    height: 37px;
    border: 1px solid #ddd;
    color: #555;
    float: left;
    border-right: 0;
    text-align: center;
  }

  .plus,
  .mins {
    width: 15px;
    text-align: center;
    height: 17px;
    line-height: 17px;
    background: #f1f1f1;
    color: #666;
    position: absolute;
    right: -8px;
    border: 1px solid #ccc;
    cursor: pointer;
    &.disabled{
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }

  .mins {
    right: -8px;
    top: 19px;
    border-top: 0;
  }

  .plus {
    right: -8px;
  }
}
</style>